package com.xv.yan.servlet;

import com.xv.yan.beans.entity.StudentDo;
import com.xv.yan.beans.req.StudentRequest;
import com.xv.yan.beans.res.TableResult;
import com.xv.yan.beans.vo.StudentVo;
import com.xv.yan.service.StudentService;
import com.xv.yan.service.impl.StudentServiceImpl;
import com.xv.yan.util.DateUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.text.ParseException;

@WebServlet(name = "StudentServlet", value = "/StudentServlet")
public class StudentServlet extends HttpServlet {
    private StudentService studentService=new StudentServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String type=request.getParameter("type");
        if ("toStudentManage".equals(type)){
            //查询出来学生列表放到request中
            String studentName = request.getParameter("studentName");
            String pageNowStr = request.getParameter("pageNow");//当前第几页
            StudentRequest studentRequest = new StudentRequest();
            int pageNow=1;//默认查第一页
            if (pageNowStr != null && ! "".equals(pageNowStr.trim())){
                pageNow=Integer.parseInt(pageNowStr);
            }
            studentRequest.setPageNow(pageNow);
            studentRequest.setStudentName(studentName);
            //接下来进行查询
            TableResult<StudentVo> tableResult=studentService.queryStudentByPage(studentRequest);
            tableResult.setPageNow(pageNow);
            tableResult.setStudentName(studentName);
            //放到request请求域中，并在studentManage.jsp中使用
            request.setAttribute("tableResult",tableResult);

            request.getRequestDispatcher("/WEB-INF/student/studentManage.jsp").forward(request,response);
        }else if ("toAdd".equals(type)){
            request.getRequestDispatcher("/WEB-INF/student/add.jsp").forward(request,response);
        }else if ("add".equals(type)){
            //执行学生的添加
            String studentName = request.getParameter("studentName");
            String no = request.getParameter("no");
            String birthDay = request.getParameter("birthDay");
            StudentDo studentDo=new StudentDo();
            studentDo.setStudentName(studentName);
            studentDo.setNo(no);
            DateUtil dateUtil = new DateUtil();
            try {
                studentDo.setBirthDay(dateUtil.DateToDate(birthDay));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            studentService.addStudent(studentDo);
            response.sendRedirect(request.getContextPath()+"/StudentServlet?type=toStudentManage");
        }

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
